package com.mvc.service.impl;

import java.util.ArrayList;
import java.util.Date;

import com.jfinal.plugin.activerecord.Page;
import com.mvc.model.CDKey;
import com.mvc.request.ReqCDKeyAdd;
import com.mvc.request.ReqCDKeyDelete;
import com.mvc.request.ReqCDKeyPage;
import com.mvc.request.ReqCDKeyQPage;
import com.mvc.request.ReturnData;
import com.mvc.response.RspPage;
import com.mvc.service.CDKeyService;

public class CDkeyServiceImpl implements CDKeyService
{

	@Override
	public ReturnData<RspPage<CDKey>> queryPage(ReqCDKeyPage req)
	{
		Page<CDKey> page = CDKey.dao.queryPage(req);
		
		RspPage<CDKey> rspPage = new RspPage<>();
		if (page != null) {
			rspPage.setNowPage(req.getNowPage());
			rspPage.setTotalPage(page.getTotalPage());
			rspPage.setList(page.getList());
		} else {
			rspPage.setNowPage(req.getNowPage());
			rspPage.setTotalPage(0);
			rspPage.setList(new ArrayList<CDKey>());
		}
		return new ReturnData<RspPage<CDKey>>(rspPage, 200, "OK");
	}

	@Override
	public ReturnData<Boolean> add(ReqCDKeyAdd req)
	{
		if (req == null) {
			return new ReturnData<Boolean>(false, 202, "error");
		}
		
		CDKey cdKey = new CDKey();
		cdKey.set(CDKey.TableField.NAME.value, req.getName());
		cdKey.set(CDKey.TableField.CREATETIME.value, new Date());
		cdKey.set(CDKey.TableField.MAC.value, req.getFinalData().getMac());
		cdKey.set(CDKey.TableField.CODEKEY.value, req.getCodeKey());
		cdKey.set(CDKey.TableField.CONTENT.value, req.getContent());
		cdKey.set(CDKey.TableField.VIABLESIZE.value, req.getViableSize());
		
		if (cdKey.save()) {
			return new ReturnData<Boolean>(true, 200, "OK");
		} else {
			return new ReturnData<Boolean>(false, 202, "error");
		}
	}

	@Override
	public ReturnData<Boolean> delete(ReqCDKeyDelete req)
	{
		if (req == null) {
			return new ReturnData<Boolean>(false, 202, "error");
		}
		CDKey car = CDKey.dao.findById(req.getId());
		if (car != null && car.delete()) {
			return new ReturnData<Boolean>(true, 200, "OK");
		} else {
			return new ReturnData<Boolean>(false, 202, "error");
		}
	}

	@Override
	public ReturnData<CDKey> queryObject(ReqCDKeyQPage req)
	{
		if (req == null) {
			return new ReturnData<CDKey>(null, 202, "error");
		}
		CDKey car = CDKey.dao.queryObject(req);
		if (car != null) {
			return new ReturnData<CDKey>(car, 200, "OK");
		} else {
			return new ReturnData<CDKey>(null, 202, "error");
		}
	}

}
